import './index.scss'
import {FC, JSX, useEffect, useRef, useState} from "react";
import {Col, Collapse, Flex, Form, Input, InputNumber, Radio, RadioChangeEvent, Row, Space, Splitter} from "antd";
import {commonButtonCollapseList} from "./common.button.list";
import CommonButtonComponent from "../../../components/form/common";
import type {CheckboxGroupProps} from "antd/es/checkbox";
import {v4 as UUID} from "uuid";
import {AndroidOutlined, WindowsOutlined} from "@ant-design/icons";
import {
    ControllerMappingInterface,
    ControllerPropertyInterface, DesignJSONInterface, DesignPropsInterface, OptionInterface, OptionJsonInterface,
} from "../../../types/interface/form.control.interface";
import OptionComponent from "../../../components/form/option";
import TranslateComponent from "../../../components/form/translate";

export const DesignComponent: FC<DesignPropsInterface> = ({design,DesignChange}) => {
    const [activeKeys, setActiveKeys] = useState<string[]>(['Container', 'Input', 'Button']);
    const [draw_type, set_draw_type] = useState<string>('computer')
    const [controller_property_form] = Form.useForm<ControllerPropertyInterface>()
    const [property_form_value, set_property_form_value] = useState<ControllerPropertyInterface>({
        id: UUID(),
        name: '默认名称',
        title: '默认标题',
        x: 0,
        y: 0,
        z: 0,
        placeholder: '默认提示文字',
        option: `{"data":[{"key": "这是键", "value": "这是值"}]}`,
        type: 'Container'
    })
    const options: CheckboxGroupProps<string>['options'] = [
        {label: <WindowsOutlined/>, value: 'computer'},
        {label: <AndroidOutlined/>, value: 'phone'},
    ];

    const design_init = JSON.parse(design) as DesignJSONInterface;
    const [controller_draw, set_controller_draw] = useState<ControllerMappingInterface[keyof ControllerMappingInterface][]>(design_init.data);
    const controller_map = useRef(new Map<string, ControllerMappingInterface[keyof ControllerMappingInterface]>());

    const updateDesignData = (newData: ControllerMappingInterface[keyof ControllerMappingInterface][]) => {
        const updatedValue: DesignJSONInterface = {
            ...design_init,
            data: newData
        };
        DesignChange(JSON.stringify(updatedValue , null,4));
    };

    const onCollapseChange = (keys: string | string[]) => {
        setActiveKeys(Array.isArray(keys) ? keys : [keys]);
    };

    // 是否为电脑画板
    const typeOnChange = (e: RadioChangeEvent) => {
        e.target.value === 'computer' ? set_draw_type('computer') : set_draw_type('phone')
    }

    // 选项值改变
    const optionValueChange = (value: string) => {
        set_property_form_value({...property_form_value, option: value})
        // 直接更新表单字段
        controller_property_form.setFieldsValue({
            option: value
        });
    }

    // 处理整个表单变化
    const onFormValuesChange = (
        changedValues: Partial<ControllerPropertyInterface>,
        componentProperty: ControllerPropertyInterface
    ) => {
        set_property_form_value(componentProperty);

        const newControllerDraw = controller_draw.map(item =>{
            if (item.id === componentProperty.id){
                return componentProperty
            }
            return item
        })

        // 添加到状态数组
        set_controller_draw(newControllerDraw);

        // 添加到 Map
        controller_map.current.set(componentProperty.id, componentProperty);

    }

    const handleComponentCreated =  (
        componentProperty: ControllerMappingInterface[keyof ControllerMappingInterface]
    ) => {
        if (componentProperty.id) {
            // 添加到状态数组
            set_controller_draw(prev => [...prev, componentProperty]);

            // 添加到 Map
            controller_map.current.set(componentProperty.id, componentProperty);
            controller_property_form.setFieldsValue(componentProperty);
            set_property_form_value(componentProperty);
        }
    };

    // 左侧折叠面板
    const collapse_control = commonButtonCollapseList.map(control => {
        return {
            key: control.key,
            label: control.label,
            children: (
                <Flex justify='space-start' wrap gap={20}>
                    {
                        control.children.map(item => {
                            return (
                                <CommonButtonComponent
                                    key={item.control}
                                    type={item.control}
                                    control={item.control}
                                    text={item.text}
                                    onComponentCreated={ handleComponentCreated }
                                />
                            )
                        })
                    }
                </Flex>

            )
        }
    })

    // 设置翻译组件点击事件
    const TranslateComponentOnClick = (id:string)=>{
        for (let item of controller_draw) {
            if (item.id === id) {
                controller_property_form.setFieldsValue(item);
                set_property_form_value(item);
            }
        }
    }

    useEffect(() => {
        controller_property_form.setFieldsValue(property_form_value);
    }, [controller_property_form]);

    useEffect(() => {
        updateDesignData(controller_draw)
    }, [controller_draw]);

    return (
        <Flex className='design-component' justify='flex-start'>
            <Flex className='left' justify="start" vertical={true}>
                <p className='title-tab'>
                    组件库
                </p>
                <Collapse defaultActiveKey={activeKeys} className='collapse' onChange={onCollapseChange}
                          ghost items={collapse_control} expandIconPosition='end'/>
            </Flex>
            <Flex className='center' justify='flex-start' vertical>
                <Flex className='tap' justify='flex-start' wrap={false} align='center'>
                    <Radio.Group
                        block
                        options={options}
                        defaultValue="computer"
                        optionType="button"
                        buttonStyle="solid"
                        onChange={typeOnChange}
                    />
                </Flex>
                <Flex className='box' justify='center'>
                    <div className={draw_type}>
                        {
                            // TODO: 修复组件可以超过画板问题
                            controller_draw.map(component => (
                                <TranslateComponent key={component.id} onClick={() => TranslateComponentOnClick(component.id)}
                                                    property={component} />
                            ))
                        }
                    </div>
                </Flex>
            </Flex>
            <Flex className='right flex-center'>
                <Splitter layout='vertical'>
                    <Splitter.Panel resizable={false} defaultSize='60%'>
                        <p className='title-tab'>
                            属性
                        </p>
                        <Form className='form'
                              form={controller_property_form}
                              onValuesChange={onFormValuesChange}
                              layout="vertical">
                            <Space>
                                <Form.Item label="X" name="x">
                                    <InputNumber/>
                                </Form.Item>
                                <Form.Item label="Y" name="y">
                                    <InputNumber/>
                                </Form.Item>
                                <Form.Item label="Z" name="z">
                                    <InputNumber/>
                                </Form.Item>
                            </Space>
                            <Form.Item label="宽度" name="width">
                                <Input/>
                            </Form.Item>
                            <Form.Item label="高度" name="height">
                                <Input/>
                            </Form.Item>
                            <Form.Item label="背景颜色" name="backgroundColor">
                                <Input/>
                            </Form.Item>
                            <Form.Item label="标题" name="title">
                                <Input/>
                            </Form.Item>

                            <Form.Item label="提示文字" name="placeholder">
                                <Input/>
                            </Form.Item>
                            <Form.Item label="选项" name="option">
                                <OptionComponent json_string={property_form_value.option}
                                                 valueChange={optionValueChange}/>
                            </Form.Item>
                            <Form.Item label="组件id" name="id" style={{display: 'none'}}>
                                <Input/>
                            </Form.Item>
                        </Form>
                    </Splitter.Panel>
                    <Splitter.Panel resizable={false}>
                        <p className='title-tab'>
                            视图
                        </p>
                    </Splitter.Panel>
                </Splitter>
            </Flex>
        </Flex>
    )
}
